package vn.qnamuni.calendar.activity;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import vn.qnamuni.calendar.services.ServiceHelper;
import android.app.ActionBar;
import android.app.Activity;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;

import android.content.Context;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.widget.Toast;

import com.facebook.LoggingBehavior;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;

public class EventActivity extends Activity {
	

	Button btn_DayMonth, btn_Time;
	Calendar myCal = Calendar.getInstance();
	
	SimpleDateFormat sdf =null;
	Button btn_fbUserID;
	//-------
	public static boolean isFaceActive;
	boolean pendingPublishReauthorization = false;
	public static boolean isActive ;//= false;
	public static String TAG ="";
	
	// start Facebook Login
	private Session.StatusCallback statusCallback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			onSessionStateChange(session, state, exception);
		}
	};

	private void onSessionStateChange(Session session, SessionState state,
	        Exception exception) {
// lấy thử		
//	    if (state.isOpened()) {
//	        Log.i(TAG, "Logged in...");
//	        Request.executeMyFriendsRequestAsync(session,
//	                new GraphUserListCallback() {
//
//	                    @Override
//	                    public void onCompleted(List<GraphUser> users,
//	                            Response response) {
//	                        Log.i("Response JSON", response.toString());
//	                       String[] names = new String[users.size()];
//	                       String[] id = new String[users.size()];
//	                       String[] bd = new String[users.size()];
//	                        for (int i=0; i<users.size();i++){
//	                            names[i] = users.get(i).getName();
//	                            id[i]= users.get(i).getId();
//	                            bd[i] = users.get(i).getBirthday();
//	                        	
//	                        }                           
//	                    }
//	                });
//	    } else if (state.isClosed()) {
//	        Log.i(TAG, "Logged out...");
//	    }
	}
	
	//DatePickerDialog 
		DatePickerDialog.OnDateSetListener d = new DatePickerDialog.OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				myCal.set(Calendar.YEAR,year);
				myCal.set(Calendar.MONTH,monthOfYear);
				myCal.set(Calendar.DAY_OF_MONTH,dayOfMonth);
				updateButtonDate();
			}
		};
	
		//TimPickerDialog 
		TimePickerDialog.OnTimeSetListener t = new TimePickerDialog.OnTimeSetListener() {
			
			@Override
			public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
				// gán giờ, phút
				myCal.set(Calendar.HOUR_OF_DAY, hourOfDay);
				myCal.set(Calendar.MINUTE,minute);
				updateButtonTime();
				
			}
		};
	
		private void updateButtonDate(){
			 sdf = new SimpleDateFormat("dd-MM-yyyy",Locale.US);
			btn_DayMonth.setText(sdf.format(myCal.getTime()));	
		}
		private void updateButtonTime(){
			sdf = new SimpleDateFormat("HH:mm:ss",Locale.US);
			btn_Time.setText(sdf.format(myCal.getTime()));
		}
	
		//-----------------Activity--------------------------	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add);
		// -----------------------------------------------------------
		if(ServiceHelper.getInstance(this).isInternetAvailable(this)){
			Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
			Session session = Session.getActiveSession();
			if (session == null) {
				if (savedInstanceState != null) {
					session = Session.restoreSession(this, null,
							statusCallback, savedInstanceState);
				}
				if (session == null) {
					session = new Session(this);
				}
				Session.setActiveSession(session);
				if (session.getState().equals(
						SessionState.CREATED_TOKEN_LOADED)) {
					session.openForRead(new Session.OpenRequest(this)
							.setCallback(statusCallback));
				}
			}
			updateView();
		}else {
			Log.v("FacebookActivity - onCreate", "No network");
		}
		//--------------------------------------
		setupActionBar();
		ActionBar actionBar = getActionBar();
		actionBar.setBackgroundDrawable(new ColorDrawable(Color
				.parseColor("#0085A8")));
		
		// get intent data
		Intent i = getIntent();
		String position = i.getStringExtra("id");
	    btn_DayMonth = (Button) findViewById(R.id.btn_DayMonth);
		btn_DayMonth.setText(position);
		
		btn_DayMonth.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				new DatePickerDialog(EventActivity.this,d,myCal.get(Calendar.YEAR),myCal.get(Calendar.MONTH),myCal.get(Calendar.DAY_OF_MONTH)).show();
				
			}
		});
		
		// Button Time
		btn_Time = (Button) findViewById(R.id.btn_Time);
		updateButtonTime();
		btn_Time.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new TimePickerDialog(EventActivity.this, t, myCal.get(Calendar.HOUR_OF_DAY), myCal.get(Calendar.MINUTE), true).show();
				
			}
		});
		
		btn_fbUserID = (Button) findViewById(R.id.btn_fbUserId);
		btn_fbUserID.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(!isActive){
					toastshow();
				}
				else{
					/// Sync
				}
			}
		});
	}
	

	public void toastshow(){
		Toast.makeText(this, "Please Log In", Toast.LENGTH_SHORT)
		.show();
	}

	@Override
	public void onStart() {
		super.onStart();
		Session.getActiveSession().addCallback(statusCallback);
	}

	@Override
	public void onStop() {
		super.onStop();
		Session.getActiveSession().removeCallback(statusCallback);
	}
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(this, requestCode,
				resultCode, data);
		if (requestCode == 100 && resultCode == 1) {
			
		}

	}
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putBoolean("saved", true);
		Session session = Session.getActiveSession();
		Session.saveSession(session, outState);
	}


//--------------------------------------------------
	private void setupActionBar() {

		getActionBar().setDisplayHomeAsUpEnabled(true);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
		    getActionBar().setHomeButtonEnabled(true);
		}

	}
	//----------------Menu-------------------------
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		getMenuInflater().inflate(R.menu.event, menu);
		MenuItem login = (MenuItem) menu.findItem(R.id.mnlogin);

		Session session = Session.getActiveSession();
		if (session.isOpened()) {
			isFaceActive = true;
		} else {
			isFaceActive = false;
		}

		if (isFaceActive) {
			login.setTitle("Log Out");
		} else {
			login.setTitle("Log In");
		}
		
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuItem login = (MenuItem) menu.findItem(R.id.mnlogin);
		Session session = Session.getActiveSession();
		if (session.isOpened()) {
			isFaceActive = true;
		} else {
			isFaceActive = false;
		}
		if (isFaceActive) {
			login.setTitle("Log Out");
		} else {
			login.setTitle("Log In");
		}

		return super.onPrepareOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:	
			NavUtils.navigateUpFromSameTask(this); // android 4.1 trở lên
		case R.id.mnlogin:
			if (!isFaceActive) {
				if (!isNetAvailable(this)) {
					Toast.makeText(this, "Sorry, network is not available",
							Toast.LENGTH_LONG).show();
				} else {
					onClickLogin();
				}

			}
			else{
				onClickLogout();
			}
			return true;
		
		}
		return super.onOptionsItemSelected(item);
	}

	//----------------
	public Boolean isNetAvailable(Context con) {

		try {
			ConnectivityManager cm = (ConnectivityManager) con
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo info = cm.getActiveNetworkInfo();
			if ((null != info) && (info.isConnectedOrConnecting())) {
				return true;
			}
		} catch (Exception e) {
			Toast.makeText(this, "Cannot connect to Network",
					Toast.LENGTH_SHORT).show();
		}
		return false;
	}
	//-----------------
	private void updateView() {

		Session session = Session.getActiveSession();
		if (session == null)
			Log.v("update", "session null");
		if (session.isOpened()) {
			Log.v("FacebookActivity - updateView", "session opened");
			isActive = true;
		} else {
			isActive = false;
			Log.v("FacebookActivity - updateView", "session closed");
		}
	}

    private void onClickLogin() {
		Session session = Session.getActiveSession();
		if (!session.isOpened() && !session.isClosed()) {
			session.openForRead(new Session.OpenRequest(this)
					.setCallback(statusCallback));

		} else {
			Session.openActiveSession(this, true, statusCallback);
		}
	}
	private void onClickLogout() {
		Session session = Session.getActiveSession();
		if (session != null) {

			if (!session.isClosed()) {
				session.closeAndClearTokenInformation();
				// clear your preferences if saved
			}
		} else {

			session = new Session(this);
			Session.setActiveSession(session);

			session.closeAndClearTokenInformation();
			// clear your preferences if saved

		}
		if (session.isOpened()) {
			isFaceActive = true;
		} else {
			isFaceActive = false;
		}

	}



}
